import { Button, ButtonGroup, styled } from '@mui/material'
import { useEffect, useReducer, useState } from 'react'
import { useAppDispatch, useAppSelector } from '../../store/hooks'
import { selectCatalogPagination } from '../../store/reducers/selectors'
import { catalogSlice } from '../../store/reducers/slices/catalogSlice'

export const DEFAULT_PAGE = 1
export const DEFAULT_ITEMS_PER_PAGE = 12

type TPagination = {
	page?: number
	selectedPage?: number
	itemsPerPage?: number
}

const StyledButton = styled(Button, {
	shouldForwardProp: (props) => props !== 'sortBy' && props !== 'selectedPage',
})<Pick<TPagination, 'page' | 'selectedPage'>>(({ page, selectedPage }) => ({
	textTransform: 'none',
	color: page === selectedPage ? '#1A1A1A' : '#7B8E98',
	fontFamily: 'Nunito',
	fontSize: '14px',
	border: '0',
}))

const Pagination = () => {
	const pagination = useAppSelector(selectCatalogPagination)
	const dispatch = useAppDispatch()

	function reducePages() {
		return Array.from({ length: pagination.maxPage }, (_, i) => i + 1).slice(
			selectedPage - 1,
			selectedPage + 2
		)
	}

	const [selectedPage, setSelectedPage] = useState(pagination.selectedPage)
	const [pages, setPages] = useReducer(reducePages, [pagination.selectedPage])

	useEffect(() => {
		dispatch(catalogSlice.actions.setPage(selectedPage))
		setPages()
	}, [dispatch, selectedPage, pagination.maxPage])

	return (
		<ButtonGroup>
			<StyledButton
				selectedPage={selectedPage}
				onClick={() => setSelectedPage(1)}
			>
				{'< Назад'}
			</StyledButton>
			{pages.map((page) => (
				<StyledButton
					key={page}
					page={page}
					selectedPage={selectedPage}
					onClick={() => setSelectedPage(page)}
				>
					{page}
				</StyledButton>
			))}
			<StyledButton
				selectedPage={selectedPage}
				onClick={() => setSelectedPage(1)}
			>
				...
			</StyledButton>
			<StyledButton
				selectedPage={selectedPage}
				onClick={() => setSelectedPage(1)}
			>
				{'Вперёд >'}
			</StyledButton>
		</ButtonGroup>
	)
}

export default Pagination
